package com.taoz.rpc.core.loadbalancer;

import cn.hutool.core.collection.CollUtil;
import com.taoz.rpc.core.model.ServiceMetaInfo;
import lombok.extern.slf4j.Slf4j;

import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
public class ConsistentHashLoadBalancer implements LoadBalancer {

    @Override
    public ServiceMetaInfo selectService(List<ServiceMetaInfo> serviceList, Map<String, Object> balanceParams) {
        log.info("正在使用 {} 获取服务", "ConsistentHashLoadBalancer");
        if (CollUtil.isEmpty(serviceList)) {
            return null;
        } else if (serviceList.size() == 1) {
            return serviceList.get(0);
        }

        TreeMap<Integer, ServiceMetaInfo> treeMap = new TreeMap<>();
        for (ServiceMetaInfo info : serviceList) {
            for (int i = 0; i < 10; i++) {
                String serviceAddress = info.getServiceAddress();
                int hash = getHash(serviceAddress + i);
                treeMap.put(hash, info);
            }
        }
        Map.Entry<Integer, ServiceMetaInfo> entry = treeMap.ceilingEntry(getHash(balanceParams));
        if (entry == null) {
            entry = treeMap.firstEntry();
        }
        return entry.getValue();
    }

    public int getHash(Object key) {
        return key.hashCode();
    }
}
